package org.example;

import com.alibaba.fastjson.JSON;
import com.entity.User;
import com.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "tbUser", value = "/user/list")
public class TestUserServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        try {
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();

            // if
            {
                Map<String, String> param = new HashMap<String, String>();
                param.put("name", "哪吒");
//                User user = sqlSession.selectOne("com.mapper.UserMapper.ifDemo", param);

                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                User user = userMapper.ifDemo(param);
                System.out.println(JSON.toJSONString(user));

                response.setContentType("text/html");
                response.setCharacterEncoding("UTF-8");

                // Hello
                PrintWriter out = response.getWriter();
                out.println("<html><body>");
                out.println("<h1>foreache-inset-成功</h1>");
                out.println("</body></html>");
            }

            // 释放资源
            sqlSession.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public void destroy() {
    }
}